<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="联络单位" prop="unitName">
        <el-input
          v-model="queryParams.unitName"
          placeholder="请输入联络单位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="postList">
      <el-table-column label="联络单位" align="center" prop="unitName" />
      <el-table-column label="联系信息" align="center" :width="600">
        <template slot-scope="scope">
          <div class="contact-container">
            <el-tag
              v-for="(item, index) in scope.row.contactList"
              :key="index"
              closable
              @click="handleEditUser(scope.row, item)"
              @close="deleteUser(item.userId)"
            >
              {{ item.userName }} {{ item.phone }} {{ truncateRemark(item.remark) }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sortOrder" :width="80"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleInsert(scope.row)"
          >新增联系信息</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/修改联络单位弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="unitform" :model="unitform" :rules="rules" label-width="80px">
        <el-form-item label="单位名称" prop="unitName">
          <el-input v-model="unitform.unitName" placeholder="请输入单位名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input v-model.number="unitform.sortOrder" placeholder="请输入排序号" type="number" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('unitform')">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 新增/修改联系信息弹窗 -->
    <el-dialog :title="contactTitle" :visible.sync="openContact" width="500px" append-to-body>
      <el-form ref="userform" :model="userform" :rules="contactRules" label-width="80px">
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="userform.userName" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="userform.phone" placeholder="请输入联系人电话" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="userform.remark" placeholder="请输入值班信息等备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitContact('userform')">保 存</el-button>
        <el-button @click="openContact = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addUser, selectUserByUnitId, deleteUser, editUser } from '@/api/system/unituser'
import { selectUnitList, addUnit, deleteUnit, updateUnit } from '@/api/system/unit'
export default {
  name: "ContactUnit",
  data() {
    return {
      showSearch: true,
      total: 0,
      postList: [],
      loading: false,
      title: "",
      open: false,
      openContact: false,
      contactTitle: "",
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        unitName: undefined // 用于传递搜索关键词
      },
      unitform: {
        unitId: null,
        unitName: '',
        sortOrder: 0
      },
      userform: {
        userId: null,
        unitId: null,
        userName: '',
        phone: '',
        remark: ''
      },
      rules: {
        unitName: [
          { required: true, message: "单位名称不能为空", trigger: "blur" }
        ],
        sortOrder: [
          { required: true, message: "排序不能为空", trigger: "blur" },
          { type: 'number', message: "排序必须为数字", trigger: "blur" }
        ]
      },
      contactRules: {
        userName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "电话不能为空", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 获取联络单位列表（直接使用接口返回的waContactUserList）
    getList() {
      this.loading = true;
      selectUnitList(this.queryParams).then(response => {
        // 接口返回数据结构：{code:200, msg:"", data: [{unitId, unitName, waContactUserList: [...]}, ...]}
        const unitList = response.data || [];
        // 转换waContactUserList为contactList，保持前端数据字段一致
        this.postList = unitList.map(unit => ({
          ...unit,
          contactList: unit.waContactUserList || [] // 直接映射关联的用户列表
        }));
        // 若接口返回total则用response.total，否则用列表长度
        this.total = response.total || unitList.length;
        this.loading = false;
      }).catch(error => {
        this.$message.error('获取联络单位列表失败：' + error.message);
        this.loading = false;
      });
    },

    // 重置表单
    reset() {
      this.unitform = {
        unitId: null,
        unitName: '',
        sortOrder: 0
      };
      if (this.$refs.unitform) {
        this.$refs.unitform.resetFields();
      }
    },

    // 取消弹窗
    cancel() {
      this.open = false;
      this.reset();
    },

    handleQuery() {
      this.queryParams.pageNum = 1; // 重置页码
      this.getList();
    },

    // 新增联络单位
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加联络单位";
    },

    // 修改联络单位
    handleUpdate(row) {
      this.reset();
      this.unitform = {
        unitId: row.unitId,
        unitName: row.unitName,
        sortOrder: row.sortOrder || 0
      };
      this.open = true;
      this.title = "修改联络单位";
    },

    // 提交联络单位表单（新增/修改）
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const requestFn = this.unitform.unitId ? updateUnit : addUnit;
          requestFn(this.unitform).then(response => {
            this.$message.success(`${this.unitform.unitId ? '修改' : '新增'}成功`);
            this.open = false;
            this.getList(); // 提交后重新获取列表（包含关联用户）
          }).catch(error => {
            let errorMsg = error.message;
            if (error.response) {
              errorMsg = `HTTP 状态码：${error.response.status}，提示：${error.response.data?.msg || '无具体错误信息'}`;
            }
            this.$message.error(`${this.unitform.unitId ? '修改' : '新增'}失败：${errorMsg}`);
          });
        }
      });
    },

    // 删除联络单位
    handleDelete(row) {
      const unitId = row.unitId;
      const unitName = row.unitName;
      this.$confirm(`是否确认删除联络单位"${unitName}"?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUnit(unitId).then(() => {
          this.$message.success("删除成功");
          this.getList(); // 重新获取列表
        }).catch(error => {
          this.$message.error("删除失败：" + error.message);
        });
      }).catch(() => {});
    },

    // 删除联系信息
    deleteUser(userId) {
      if (!userId) return this.$message.error('用户ID不能为空');
      // 查找用户所在的单位
      const unit = this.postList.find(u =>
        u.contactList.some(contact => contact.userId === userId)
      );
      if (!unit) return this.$message.error('找不到用户信息');
      // 获取用户姓名用于确认提示
      const contact = unit.contactList.find(c => c.userId === userId);
      const userName = contact?.userName || '此用户';
      this.$confirm(`确定要删除用户"${userName}"吗？`, '确认删除', {
        type: 'warning'
      }).then(() => {
        deleteUser(userId).then(() => {
          // 本地过滤删除的用户，同时重新拉取列表确保数据一致
          unit.contactList = unit.contactList.filter(c => c.userId !== userId);
          this.$message.success('删除成功');
          this.getList(); // 重新获取列表，避免本地数据与后端不一致
        }).catch(error => {
          this.$message.error(`删除失败: ${error.message}`);
        });
      });
    },

    // 打开新增联系信息弹窗
    handleInsert(row) {
      this.contactTitle = "新增联系信息";
      this.userform = {
        userId: null,
        unitId: row.unitId,
        userName: '',
        phone: '',
        remark: ''
      };
      this.openContact = true;
    },

    // 打开修改联系信息弹窗
    handleEditUser(row, item) {
      this.contactTitle = "修改联系信息";
      this.userform = {
        userId: item.userId,
        unitId: row.unitId,
        userName: item.userName,
        phone: item.phone,
        remark: item.remark
      };
      this.openContact = true;
    },

    // 提交联系信息表单
    submitContact(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const requestFn = this.userform.userId ? editUser : addUser;
          requestFn(this.userform).then(response => {
            this.$message.success(`${this.userform.userId ? '修改' : '新增'}联系信息成功`);
            this.openContact = false;
            this.getList(); // 提交后重新获取列表，更新联系信息
          }).catch(error => {
            this.$message.error(`${this.userform.userId ? '修改' : '新增'}联系信息失败：${error.message}`);
          });
        }
      });
    },

    // 备注截断处理
    truncateRemark(remark, maxLength = 12) {
      if (!remark || remark.length <= maxLength) {
        return remark;
      }
      return remark.substring(0, maxLength) + '...';
    }
  }
};
</script>

<style scoped>
/* 联系信息标签样式 */
.el-table-column .el-tag {
  background-color: white;
  color: black;
  padding: 8px 12px;
  border: 1px solid black;
  margin-right: 8px;
  margin-bottom: 8px;
}

/* 标签关闭按钮样式 */
.el-table-column .el-tag .el-tag__close {
  color: black;
}

.contact-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px; /* 统一设置间距 */
}

.contact-container .el-tag {
  width: calc(50% - 6px);
  margin: 0;
}
</style>
